<template>
    <div class="search-index">
      <form action="/" class="search-form">
        <van-search
          v-model="searchText"
          show-action
          placeholder="请输入搜索关键词"
          background="#3296fa"
          @search="onSearch"
          @cancel="onCancel"
          @focus="isResultShow = false"
        />
      </form>

       <!-- 搜索结果 -->
      <searchresult v-if="isResultShow" :searchText='searchText'></searchresult>
      <!-- /搜索结果 -->

      <!-- 搜索建议 -->
      <searchJianyi v-else-if="searchText" :searchText='searchText' @search='onSearch'></searchJianyi>
      <!-- /搜索建议 -->

      <!-- 搜索历史 -->
      <searchLishi v-else :search-histories="searchHistories" @search='onSearch'></searchLishi>
      <!-- /搜索历史 -->

    

     
    </div>
</template>

<script>
import searchLishi from './components/searchLishi.vue'
import searchJianyi from './components/searchJianyi.vue'
import searchresult from './components/searchresult.vue'
import {setItem,getItem} from '@/utils/storage'

export default {
  name: 'Searchindex',
  props: {},
  components: {
    searchLishi,
    searchJianyi,
    searchresult
  },
  data () {
   return {
      searchText:'', // 搜索框的文本值\
      isResultShow: false, // 控制搜索结果的显示与否
      searchHistories:getItem('TOUTIAO_SEARCH_HISTORIES') || [] // 存储历史记录
   }
  },
  computed: {},
  watch: {
    // 数据持久化，实时监听最新数据
    searchHistories(value) {
      setItem('TOUTIAO_SEARCH_HISTORIES',value)
    }
      
    
  },
  methods: {
     onSearch (val) { //val：输入的关键字
        // 更新搜索框的内容
        this.searchText = val
        // 要求：不要有重复历史记录、最新的排在最前面
        const index = this.searchHistories.indexOf(val)
        if(index !== -1) { // 如果重复，则先删除，然后再头部添加
          this.searchHistories.splice(index,1)
        }
        this.searchHistories.unshift(val)  // 在头部添加

        // 渲染搜索结果
	      this.isResultShow = true
    },
     onCancel () {
     this.$router.back() //返回上一页（首页）
    }
  },
  created () {
  },
  mounted () {
  },
}
</script> 

<style scoped lang="less">
.search-index {
  padding-top: 108px;
	.van-search__action {
		color: #fff;
	}
  .search-form {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1;
	}
}
</style>